package it.polimi.jita.cp.rs;

import it.polimi.jita.cp.block.Block;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.csv.CSVRecord;
import org.jfree.chart.JFreeChart;

public class RandomStress extends Block<RandomStressInput, RandomStressOutput> {

	private final static String SCRIPT_NAME = "cpuload.sh";

	@Override
	protected RandomStressOutput computeOutput() {
		// Read script from jar
		copyAndPasteCPULoadScript();
		Integer demand = 50;
		Integer second = 120;
		callCPULoad(demand, second);
		// deleteScript();
		return null;
	}

	private void callCPULoad(Integer demand, Integer second) {
		File file = new File(SCRIPT_NAME);
		file.setExecutable(true);
		ProcessBuilder pb = new ProcessBuilder(file.getAbsolutePath(),
				demand.toString(), second.toString());
		try {
			Process p = pb.start();
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			System.out.println(br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Problem running the script");
		}
		// catch (InterruptedException e) {
		// e.printStackTrace();
		// System.out.println("Problem waiting the script");
		// }
	}

	private void deleteScript() {
		try {

			File file = new File(SCRIPT_NAME);
			if (file.delete()) {
				// System.out.println(file.getName() + " is deleted!");
			} else {
				System.out.println("Delete operation is failed.");
			}

		} catch (Exception e) {

			e.printStackTrace();

		}
	}

	private void copyAndPasteCPULoadScript() {
		InputStream is = getClass().getResourceAsStream("/" + SCRIPT_NAME);
		OutputStream resStreamOut;
		int readBytes;
		byte[] buffer = new byte[4096];
		try {
			resStreamOut = new FileOutputStream(new File(SCRIPT_NAME));
			while ((readBytes = is.read(buffer)) > 0) {
				resStreamOut.write(buffer, 0, readBytes);
			}
			resStreamOut.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected Set<JFreeChart> createCharts() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected Map<List<CSVRecord>, CSVRecord> createCSVFiles() {
		// TODO Auto-generated method stub
		return null;
	}

}
